const { ProductModel } = require("../../models/ProductModel")
import { CategoryModel } from "../../models/CategoryModel.js"
import Dialog from '../../components/dist/dialog/dialog';
import Toast from '../../components/dist/toast/toast';
import { NoticeModel } from '../../models/NoticeModel.js'
const AUTO = require('../../utils/auth.js')
let Notice = new NoticeModel()
let Category = new CategoryModel()
let Product = new ProductModel()
let App = getApp()
// pages/scroll/scroll.js
Page({

    data: {
        winHeight: '100%',
        toView: 'p1',//锚点跳转的ID
        anchorArray:[],
        autoHeight:0,
        selectType:1,
        menuType:1,
        menuItem:{},
        menu:[],
        selectProducts:[],//选中的商品信息
        totalPrice:0.00,
        sumCount:0,
        show:false,//控制弹出层
        cartProducts:[],
        popupHeight:0,//弹出层高度
        count:0,
        shopStatus:false,
        notices:[],//公告
        wxlogin:false
  
       
    },
    onLoad:function(){
        this._checkLogin()
        this._getNotice()
        this._getMenuItem()
        let shopStatus = App.globalData.shopStatus 
        this.setData({shopStatus})

    },

    onShow:function(){
        // let menu = this.data.menu
        // menu.sort(this._compare)
        // this.setData({menu})
    },
    _checkLogin:function(){
        AUTO.checkLogin().then(res=>{
          this.setData({
            wxlogin:res
          })
        })
      },
     //点击 取消登录
     cancelLogin:function() {
        this.setData({
          wxlogin: true
        })
      },
      //点击 授权登录
      processLogin:function(){
        this.cancelLogin()
      },
    // 自定义浮点数加法
     _floatAdd:function(arg1,arg2){ 
        var r1,r2,m;  
        try{
        　　r1 = arg1.toString().split(".")[1].length;
        }catch(e){r1=0}  try{
        　　r2 = arg2.toString().split(".")[1].length;}catch(e){r2=0}m = Math.pow(10,Math.max(r1,r2));
        return (arg1*m+arg2*m)/m;
    },
    // 自定义浮点数减法
    _floatSub:function(arg1,arg2){
        var r1,r2,m,n;
        try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
        try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
            m=Math.pow(10,Math.max(r1,r2));    
        //动态控制精度长度  
            n=(r1>=r2)?r1:r2;    
        return((arg1*m-arg2*m)/m).toFixed(n);
    }, 
    // 自定义排序比较方法
    _compare:function (prop) {
        return function (obj1, obj2) {
            var val1 = obj1[prop];
            var val2 = obj2[prop];if (val1 < val2) {
                return -1;
            } else if (val1 > val2) {
                return 1;
            } else {
                return 0;
            }            
        } 
    },
    // 弹出 弹出层商品购物车
    showPopup:function(){
        let sumCount = this.data.sumCount
        // 购物车为空 不可查看购物车
        if(sumCount.length <= 0){
            return
        }
        this.getPopupHeight()
        //商品种类  计算弹出框的动态高度 商品列表种类*单个列表高度 + 底部结算高度100 + 购物车标题头部60 + 留白 40
        // let height = selectProducts.length * 150 + 100 + 60 + 40
        this.setData({
            show:true,
        })
    },
    // 动态获取弹出层高度
    getPopupHeight:function(){
        let menu = this.data.menu
        //商品种类  计算弹出框的动态高度 商品列表种类*单个列表高度 + 底部结算高度100 + 购物车标题头部60 + 留白 40
        // let height = selectProducts.length * 150 + 100 + 60 + 40
        let height = 200
        for(let i = 0;i<menu.length;i++){
            if(menu[i].count > 0){
                for(let j=0;j<menu[i].products.length;j++){
                    if(menu[i].products[j].select_count > 0){
                        height += 150
                    }
                }
            }
        }
        this.setData({
            popupHeight:height
        })
    },
    // 关闭弹窗
    onClose:function(){
        this.setData({
            show:false
        })
    },
    // 删除商品购物车
    clearCart:function(){
        let that = this
        Dialog.confirm({
            title: '删除',
            message: '确认清除购物车',
          })
            .then(() => {
              that.reset()
              that.setData({
                  show:false
              })
            })
            .catch(() => {
              // on cancel
            });
    },
    // 清理购物车后：归零商品选中数量 
    _initProductCounts:function(products){
        for(let i=0;i<products.length;i++){
            products[i].select_count = 0
        }
        return products
    },
    // 重置商品数据
    _initMenu: async function(category){
        let product = {
            category_type:category.category_type
        }
        let products = await Product.getProduct(product)

        products = this._initProductCounts(products)
        category.products = products
        category.count = 0
        let menu = this.data.menu
        menu.push(category)
        menu.sort(this._compare('category_type'))
        this.setData({menu})
        this._initScroll()
    },
    // 获取公告
    _getNotice: async function(){
        let notice = {release:true}
        let res = await Notice.getNotice( notice)
        this.setData({
            notices:res
        })
    },
    // 获取分类列表
    _getMenuItem:async function(){
        let menuItem = {}
        let categories = await Category.getCategory({})
        for(let i=0;i<categories.length;i++){
            menuItem = categories[i]
           this._initMenu(menuItem)
        }
    },

    _initScroll:function(){
        let autoHeight = wx.getSystemInfoSync().windowHeight * 2
        this.setData({
            autoHeight: autoHeight ,
          })

        let query = wx.createSelectorQuery().in(this);
        let heightArr =[];
        let h = 0;
        query.selectAll('.type').boundingClientRect((react)=>{
            react.forEach((res)=>{
                h+=res.height;
                let item = {
                    height:h,
                    id:res.id
                }
                heightArr.push(item)
            })
            this.setData({
                anchorArray:heightArr
            });
        }).exec();
    },
    // 当点击商品的增加按钮时，更新相关数据
    _addMenuCount:function(product){
        let menu = this.data.menu
        let sumCount = this.data.sumCount
        let totalPrice = this.data.totalPrice
        for(let i = 0; i<menu.length;i++){
            if(menu[i].category_type == product.category_type){
                sumCount ++
                menu[i].count ++
                totalPrice = this._floatAdd(totalPrice,product.product_sell_price)
                this.setData({
                    menu:menu,
                    totalPrice:totalPrice,
                    sumCount:sumCount
                })
                // this._getShopStatus()
                break;
            }
        }
    },
    // 当点击商品的减少按钮时，更新相关数据
    _subMenuCount:function(product){
        
        let menu = this.data.menu
        let sumCount = this.data.sumCount
        let totalPrice = this.data.totalPrice
        for(let i = 0; i<menu.length;i++){
            if(menu[i].category_type == product.category_type){
                sumCount = sumCount - 1
                totalPrice = this._floatSub(totalPrice,product.product_sell_price)
                menu[i].count = menu[i].count - 1
                this.setData({
                    menu:menu,
                    totalPrice:totalPrice,
                    sumCount:sumCount
                })
                // this._getShopStatus()
                break;
            }
        }
    },
    // 更新选中商品的数量：menu.products[i].select_count
    _updateSelectProducts:function(product){
        let menu = this.data.menu
        for(let i=0;i<menu.length;i++){
            if(menu[i].category_type == product.category_type){
                for(let j=0;j<menu[i].products.length;j++){
                    if(menu[i].products[j]._id == product._id){
                        menu[i].products[j].select_count = product.select_count 
                        this.setData({
                            menu:menu
                        })
                        break
                    }
                }
            }
        }
    },
    // 增加商品数量
    addCount:function(e){
        let product = e.detail.product
        this._updateSelectProducts(product)
        this._addMenuCount(product)
        // console.log('sumcount',this.data.menu)
       
    },
    // 减少商品数量
    subCount:function(e){
        let product = e.detail.product
        this._updateSelectProducts(product)
        this._subMenuCount(product)
        this.getPopupHeight()
    },
    
    // 将所有商品选中数量重置 0
    reset:function(){
        let menu = this.data.menu
        for(let i=0;i<menu.length;i++){
            menu[i].count = 0
            menu[i].products = this._initProductCounts(menu[i].products)
        }
        this.setData({
            menu:menu,
            selectProducts:[],
            sumCount:0,
            totalPrice:0,
        })
    },
    // 更新提交按钮文字
    _getShopStatus:function(){
        let totalPrice = this.data.totalPrice
        let status = false
        if(totalPrice > 0){
            status = true
        }else{
            status = false
        }
        this.setData({
            shopStatus:status
        })
    },
    // 点击左侧分类种类，重新定位右侧
    clickMenu:function(e){
        let category_type = e.currentTarget.dataset.category_type
        let viewID = 'v'+category_type
        this.setData({
            toView:viewID,
            menuType:category_type
        })
    },
    // 滑动右侧商品
    handelScroll(e) {
        let scrollTop=e.detail.scrollTop;
        let scrollArr= this.data.anchorArray;

        if(scrollTop>=scrollArr[scrollArr.length-1].height){
            return
        }else{
            for(let i=1;i<scrollArr.length;i++){
                if(scrollTop >= 0 && scrollTop < scrollArr[0].height){
                    this.setData({
                        menuType: parseInt(scrollArr[0].id.slice(1))
                    })
                }else if(scrollTop>scrollArr[i-1].height&&scrollTop<=scrollArr[i].height){
                    this.setData({
                        menuType: parseInt(scrollArr[i].id.slice(1)) 
                    })
                }
               
            }
           
        }

        if(scrollTop>=scrollArr[scrollArr.length-1]-this.data.autoHeight){
                return;
          }else {
              for(let i=0;i<scrollArr.length;i++){
                    if(scrollTop>=0&&scrollTop<scrollArr[0]){
                    // selectFloorIndex控制筛选块高亮显示
                        this.setData({
                            selectFloorIndex: 0
                        });
                    }else if(scrollTop>=scrollArr[i-1]&&scrollTop<scrollArr[i]) {
                        this.setData({
                            selectFloorIndex: i
                        });
                 }
             }
         }
    },
    // 提交
    submit:function(){
        let shopStatus = this.data.shopStatus
        let menu = this.data.menu
        let products = []
        let order = {}
        let sumCount = 0
        // 如果未营业
        if(!shopStatus){
            return
        }else{
            if(this.data.totalPrice <= 0){
                Toast.fail('请先选择商品!')
                return
            }
            for(let i=0;i<menu.length;i++){
                for(let j=0;j<menu[i].products.length;j++){
                    if(menu[i].products[j].select_count > 0){
                        let product = {}
                        product._id = menu[i].products[j]._id
                        product.product_name = menu[i].products[j].product_name
                        product.product_image = menu[i].products[j].product_image
                        // product.product_image = menu[i].products[j].product_image.substring(65)
                        product.product_sell_price = menu[i].products[j].product_sell_price
                        product.product_count = menu[i].products[j].select_count
                        sumCount += product.product_count
                        // prefix = menu[i].products[j].product_image.substring(0,65)
                        products.push(product)
                    }
                }
            }
            order.products = products
            order.total_price = this.data.totalPrice
            order.sumCount = sumCount
            try {
                wx.clearStorageSync()
              } catch(e) {
                // Do something when catch error
              }
            wx.setStorageSync('orderData', order)
           
            wx.navigateTo({
              url: '/pages/order/order' ,
            })
        }
    },
  

})